﻿using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using System.Linq;

namespace CodeAnalysisRuleCollection.Common
{
    internal static class CompilationUnitSyntaxExtensions
    {
        public static CompilationUnitSyntax WithUsing(this CompilationUnitSyntax root, string name)
        {
            if (!root.Usings.Any(u => u.Name.ToString() == name))
                return root.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(name)).WithAdditionalAnnotations(Formatter.Annotation));

            return root;
        }
    }

    internal static partial class TypeExtensions
    {
        public static TypeDeclarationSyntax WithoutBackingField(this TypeDeclarationSyntax node, string name, Workspace workspace, out EqualsValueClauseSyntax initializer)
        {
            if (
                (var declarationSyntax = node.ChildNodes().OfType<FieldDeclarationSyntax>()
                    .SelectMany(f => f.Declaration.Variables)
                    .SingleOrDefault(v => v.Identifier.ValueText == name)) != null
            )
            {
                initializer = declarationSyntax.Initializer;

                var fieldSyntax = declarationSyntax.FirstAncestorOrSelf<FieldDeclarationSyntax>();

                var nodeToRemove = fieldSyntax.Declaration.Variables.Count == 1 ? fieldSyntax as SyntaxNode : declarationSyntax;
                return node.RemoveNode(nodeToRemove, default(SyntaxRemoveOptions));
            }

            initializer = null;
            return node;

        }
    }
}
